"""
数据模型
"""

from . import db
from flask_login import UserMixin
from . import login_manager
from datetime import datetime
from flask import current_app as app


class User(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    password_hash = db.Column(db.String(128), nullable=False)
    blockchain_address = db.Column(db.String(120), nullable=False)


# class Node(db.Model):
#     node_address = db.Column(db.String(120), private_key=True, nullable=False)
#     is_active = db.Column(db.Boolean, default=True)
#     last_updated = db.Column(db.DateTime, nullable=False)

class Data(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    server_address = db.Column(db.String(120), nullable=False)
    data_name = db.Column(db.String(120), nullable=False)
    file_path = db.Column(db.String(150), nullable=False)
    timestamp = db.Column(db.DateTime, default=datetime.utcnow)
    status = db.Column(db.Integer, default=0)

class DetectionNode(db.Model):
    node_address = db.Column(db.String(120), primary_key=True)
    is_active = db.Column(db.Boolean, default=True)
    last_updated = db.Column(db.DateTime, default=datetime.utcnow)

@login_manager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))

def upgrade():
    with app.app_context():
        # 创建所有表
        db.create_all()

        # 确保 status 列存在
        db.engine.execute('ALTER TABLE data ADD COLUMN status TEXT')


